package com.itcast.controller;

import com.itcast.pojo.Result;
import com.itcast.utils.AliOSSUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
@Api(tags = "文件管理")
public class UploadController {

    @Autowired
    private AliOSSUtils aliOSSUtils;

    /**
     * 本地存储文件
     */
    /*@PostMapping("/upload")
    public Result upload(String username, Integer age, MultipartFile image) throws Exception {

        log.info("文件上传：{}，{}，{}", username, age, image);
        //获取原始文件名
        String originalFilename = image.getOriginalFilename();
        log.info("原始文件名：{}", originalFilename);

        //构造唯一的文件名(不能重复) - uuid(通用唯一识别码) c6b09b01-f7c6-42e2-9917-e3bc51bc72ec
        int index = originalFilename.lastIndexOf(".");
        String extname = originalFilename.substring(index);
        String newFileName = UUID.randomUUID().toString() + extname;
        log.info("新的文件名：{}", newFileName);

        //将接收到在服务器的磁盘目录 D:\images
        image.transferTo(new File("D:\\images\\" + newFileName));

        return Result.success();
    }*/
    @ApiOperation(value = "阿里云OSS文件上传", notes = "文件上传的说明")
    @PostMapping("/upload")
    public Result upload(@ApiParam(value = "图片文件", required = true) MultipartFile image) throws IOException {

        log.info("文件上传，文件名：{}", image.getOriginalFilename());

        //调用阿里云OSS工具类进行文件上传
        String url = aliOSSUtils.upload(image);
        log.info("文件上传完成，文件访问的url：{}", url);

        return Result.success(url);
    }

}
